const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');

// 自动发现环境配置文件
function discoverEnvironments() {
  const envFiles = fs.readdirSync('.')
    .filter(file => file.startsWith('.env.') && file !== '.env.development')
    .sort();
  
  const environments = [];
  
  for (const envFile of envFiles) {
    const mode = envFile.replace('.env.', '');
    const envPath = path.join('.', envFile);
    
    try {
      // 读取环境配置文件获取页面标题
      const envContent = fs.readFileSync(envPath, 'utf8');
      const titleMatch = envContent.match(/VUE_APP_TITLE\s*=\s*(.+)/);
      const name = titleMatch ? titleMatch[1].trim() : mode;
      
      environments.push({
        name: name,
        mode: mode,
        outputDir: `dist-${mode}`,
        envFile: envFile
      });
    } catch (error) {
      console.warn(`⚠️  无法读取配置文件 ${envFile}:`, error.message);
    }
  }
  
  return environments;
}

// 自动发现环境配置
const environments = discoverEnvironments();

console.log(`🚀 开始批量打包${environments.length}个环境配置...\n`);

if (environments.length === 0) {
  console.log('❌ 未发现任何环境配置文件！');
  console.log('请确保项目根目录下存在 .env.* 格式的配置文件（除了 .env.development）');
  process.exit(1);
}

// 清理旧的dist目录
if (fs.existsSync('dist')) {
  console.log('🧹 清理旧的dist目录...');
  fs.rmSync('dist', { recursive: true, force: true });
}

// 创建主dist目录
fs.mkdirSync('dist', { recursive: true });

let successCount = 0;
let failCount = 0;

// 逐个打包每个环境
environments.forEach((env, index) => {
  console.log(`\n📦 [${index + 1}/${environments.length}] 正在打包 ${env.name} (${env.mode})...`);
  
  try {
    // 设置环境变量并执行打包
    const buildCommand = `cross-env NODE_ENV=production BUILD_OUTPUT_DIR=${env.outputDir} vue-cli-service build --mode ${env.mode}`;
    
    console.log(`   执行命令: ${buildCommand}`);
    
    execSync(buildCommand, { 
      stdio: 'inherit',
      cwd: process.cwd(),
      env: {
        ...process.env,
        NODE_ENV: 'production',
        BUILD_OUTPUT_DIR: env.outputDir
      }
    });
    
    // 将打包结果移动到dist目录下的子目录
    const sourceDir = env.outputDir;
    const targetDir = path.join('dist', env.mode);
    
    if (fs.existsSync(sourceDir)) {
      if (fs.existsSync(targetDir)) {
        fs.rmSync(targetDir, { recursive: true, force: true });
      }
      fs.renameSync(sourceDir, targetDir);
      console.log(`   ✅ ${env.name} 打包成功 -> dist/${env.mode}/`);
      successCount++;
    } else {
      throw new Error(`打包输出目录 ${sourceDir} 不存在`);
    }
    
  } catch (error) {
    console.error(`   ❌ ${env.name} 打包失败:`, error.message);
    failCount++;
  }
});

// 生成打包报告
console.log('\n' + '='.repeat(50));
console.log('📊 打包完成报告');
console.log('='.repeat(50));
console.log(`✅ 成功: ${successCount} 个环境`);
console.log(`❌ 失败: ${failCount} 个环境`);
console.log(`📁 输出目录: dist/`);

if (successCount > 0) {
  console.log('\n📂 生成的目录结构:');
  const distContents = fs.readdirSync('dist');
  distContents.forEach(dir => {
    console.log(`   dist/${dir}/`);
  });
}

if (failCount > 0) {
  console.log('\n⚠️  请检查失败的打包日志并重试');
  process.exit(1);
} else {
  console.log('\n🎉 所有环境打包完成！');
}
